import React, { PureComponent } from 'react'
import { StyleSheet, Text, View, ScrollView } from 'react-native'
import * as _ from 'lodash'
import { WhiteSpace } from 'antd-mobile'
import Spinner from 'react-native-loading-spinner-overlay'
import { connect } from 'react-redux'
import { createAction, NavigationActions } from '../../utils'
import * as Libs from '../../utils/Libs'
import screen from '../../utils/screen'
import { LineChart, OwnCard, Summary, ButtonGroup, PullView, ViewMoreText } from '../../widgets'

const buttons = ['总资产', '总负债', '所有者权益']

@connect(({ home, assetliability, loading }) => ({ ...home, ...assetliability, isLoading: loading.models.assetliability}))
export default class extends PureComponent {
  constructor(props){
    super(props)
    this.state = {
      idx: 0 //图形 idx
    }
  }

  componentWillMount() {
    this.props.dispatch(createAction("assetliability/initState")({}))
  }

  componentDidMount() {
    const { mainTime } = this.props;
    this.loadContent(mainTime.startTime, mainTime.endTime)
  }

  componentWillReceiveProps(nextProps) {
    const mainTime= this.props.mainTime;
    const nextMainTime = nextProps.mainTime;
    console.log('asset liability receive props.')
    if(nextMainTime.startTime === undefined || nextMainTime.endTime === undefined) {
      return false
    }
    if(nextMainTime.startTime !== mainTime.startTime || nextMainTime.endTime !== mainTime.endTime) {
      this.loadContent(nextMainTime.startTime, nextMainTime.endTime)
    }
  }

  loadContent = (startT, endT) => {
    console.log('asset liability load content .')
    this.props.dispatch(createAction("assetliability/getAssetLiabilityMainMsg")({
      startTime: startT,
      endTime: endT
    }))
    this.props.dispatch(createAction("assetliability/getContentMsg")({
      startTime: startT,
      endTime: endT
    }))
    this.props.dispatch(createAction("assetliability/getAssetLiabilityModelCompare")({
      startTime: startT,
      endTime: endT
    }))
  }

  geneSummary = (summary = {}) => {
    const zzc = summary.zzc || {}
    const fz = summary.fz || {}
    const qy = summary.qy|| {}
    return [{
      zi: '资产总计',
      chou: (zzc.onRise || 0),
      yin: zzc.showMoney || 0
    },{
      zi: '负债总计',
      chou: (fz.onRise || 0),
      yin: fz.showMoney || 0
    },{
      zi: '所有者权益',
      chou: (qy.onRise || 0),
      yin: qy.showMoney || 0
    }]
  }

  renderChartOptions = (text, legends, xAxisDatas, datas, additionalD = {}) => {
    const tbs = _.map(additionalD, (v) => {
      return v.tb
    })
    const hbs = _.map(additionalD, (v) => {
      return v.hb
    })
    const option = {
      title : {
        show: false,
        text: text,
      },
      grid: {
        containLabel: true
      },
      tooltip : {
        trigger: 'axis',
        formatter: function(datas, ticket, callback) {
          const axisDatas = datas[0].name || {}
          let res = axisDatas.time + '<br/>', val;
          for(var i = 0, length = datas.length; i < length; i++) {
            val = datas[i].value;
            res += datas[i].seriesName + '：' + val + '<br/>';
          }
          res += "同比：" + axisDatas.tb + "%" + '<br/>'
          res += "环比：" + axisDatas.hb + "%" +  '<br />'
          return res;
        }
      },
      legend: {
        bottom: 'bottom',
        data: legends
      },
      xAxis : [
        {
          type : 'category',
          top: 'bottom',
          data : xAxisDatas,
          axisLabel: {
            formatter: function(value = {}, idx) {
              return value.time || ""
            }
          }
        }
      ],
      yAxis : [
        {
          type : 'value',
          name: '金额(万元)',
        }
      ],
      series : [
        {
          name: legends[0],
          type:'line',
          data: datas[0],
        },
        {
          name: legends[1],
          type:'line',
          data: datas[1],
        }
      ]
    };
    return option
  }


  render() {
    const { idx } = this.state
    const { assetLiabilitySummary,mainTime,isLoading, zzc, fz, qy, yj,gy } = this.props;
    const summaryD = this.geneSummary(assetLiabilitySummary)
    const times = assetLiabilitySummary.times
    const legends = ['本期', '上期', '同比', '环比']

    const lineOptions = this.renderChartOptions('', legends, zzc.xAxisDatas, zzc.lineDatas, zzc.additionalD)
    const twoLineOptions = this.renderChartOptions('', legends, fz.xAxisDatas, fz.lineDatas, fz.additionalD)
    const threeLineOptions = this.renderChartOptions('', legends, qy.xAxisDatas, qy.lineDatas, qy.additionalD)
    return (
      <PullView onPullRelease={() => {
        this.loadContent(mainTime.startTime, mainTime.endTime)
      }}>
        <Spinner visible={isLoading} />
        <View style={styles.summary}>
          <Summary onCellPress={() =>{
            this.props.navigation.navigate('AssetLiabilityStack', {
              initTime: mainTime
            })
          }} content={summaryD} times={times}/>
        </View>
        <WhiteSpace />
        <OwnCard title="概述" extra="报表明细" extraOnPress={() => {
          this.props.navigation.navigate('AssetLiabilityStack', {
            initTime: mainTime
          })
        }}>
          <ViewMoreText>
            {gy}
          </ViewMoreText>
        </OwnCard>
        <WhiteSpace />
        <OwnCard title="预警">
          <ViewMoreText>
            {yj}
          </ViewMoreText>
        </OwnCard>
        <WhiteSpace />
        <OwnCard title="主要指标变动趋势">
          <ButtonGroup
            onPress={(idx) => {
              console.log('press idx ', idx)
              this.setState({idx: idx})
            }}
            selectedIndex={idx}
            buttons={buttons}
          />
          {
            idx === 0 && (
              <LineChart options={lineOptions} />
            )
          }
          {
            idx === 1 && (
              <LineChart options={twoLineOptions} />
            )
          }
          {
            idx === 2 && (
              <LineChart options={threeLineOptions}/>
            )
          }
        </OwnCard>
      </PullView>
    )
  }
}

const styles = StyleSheet.create({
  summary: {
    paddingHorizontal: screen.pxToDp(26),
    backgroundColor: 'white',
  },
})
